package panda.metainfo;

import panda.transaction.*;
import panda.record.*;
import panda.query.struct.*;
import static java.sql.Types.*;

public class ViewManager {
	public static final int MAXVIEWDEF = 1000;
	private TableManager tblmgr;

	ViewManager(boolean isNew, TableManager tm, Transaction tx) {
		tblmgr = tm;

		if (isNew) {
			Schema sch = new Schema();
			sch.addAttribute(new SemAttribute("viewname"), VARCHAR,
					tblmgr.MAXNAMESIZE);
			sch.addAttribute(new SemAttribute("viewdef"), VARCHAR, MAXVIEWDEF);
			tblmgr.createTable("view", sch, tx);
		}
	}
	
	public void createView(String name, String def, Transaction tx) {
		TableToken tt = tblmgr.getTableToken(name, tx);
		RecordFile vRf = new RecordFile(tt, tx);
		
		vRf.insert();
		vRf.setString("viewname", name);
		vRf.setString("viewdef", def);
		vRf.close();
	}
	
	public String getViewDef(String name, Transaction tx) {
		TableToken tt = tblmgr.getTableToken(name, tx);
		RecordFile vRf = new RecordFile(tt, tx);
		
		String def = null;
		
		while (vRf.next()) {
			if (vRf.getString("viewname").equals(name)) {
				def = vRf.getString("viewdef");
				break;
			}
		}
		vRf.close();
		
		return def;
	}
}